package org.orbis.connect;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.orbis.communicate.Configuration;
import org.orbis.communicate.MainService;
import org.orbis.communicate.node.Node;
import org.orbis.tool.Header;

/**
 * Instantize search service.
 * 
 *  In this version, if you use this package with Tomcat, You must call "orbis/connect" to
 * open server and allocate memory block to keep data to search. Otherwise Tomcat server 
 * is might be shut illegally and would not run.
 * 
 * @author Yusuke Fujisaka (@ceeflyer)
 */
public class Connector extends HttpServlet{
	private static final long serialVersionUID = -6355247317500753454L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
		IOException{
		resp.setCharacterEncoding("UTF-8");
		String otherNode = req.getParameter("address");
		String homeDir = System.getProperty("catalina.home").concat("/");
		
		try{
			MainService.instantize(otherNode, homeDir);
		}catch(InterruptedException e){
			e.printStackTrace();
			resp.sendError(500);
			return;
		}
		
		PrintWriter out = resp.getWriter();
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
		out.println("<title>ORBIS search system: startup</title>");
		out.println("</head>");
		out.println("<body>");
		// Title bar
		out.println(Header.getTitleBar("ORBIS Search System: Startup"));

		// Header
		out.println(Header.getHeader(-1));

		out.println("<p>");
		out.println("Server established. <br>");
		out.println("</p>");
		MainService mainInst = MainService.getInstance();
		Configuration conf = mainInst.getConf();
		Node myNode = conf.myNode();
		out.println("<p>");
		out.println("My node: <b>" + myNode.getAddr() + ":" + myNode.getPort() + "</b><br>");
		if(otherNode == null) out.println("No connection for now.<br>");
		else out.println("Connect with " + otherNode + ".");
		out.println("To connect another node, startup Tomcat and call ");
		out.println("http://xxx.xxx.xxx.xxx:xxxx/orbis/connect?address=" + myNode.getAddr() + ":" + myNode.getPort());
		out.println("</p>");
		out.println("<p>");
		if(mainInst.isStartupFromBackup()) 
			out.println("Backup found. Data is recovered from backup file.");
		else
			out.println("Backup not found. This starts up gracefully.");
		out.println("</p>");
		out.println("<p>");
		out.println("<span style=\"margin: 10px; padding: 10px; background: #cccccc;\">");
		out.println("<a href=\"status\">Show status</a>");
		out.println("</span>");
		out.println("</p>");
		out.println("</body>");
		out.println("</html>");
	}
}
